package com.chinaunicom.order.domain.service;

import com.alibaba.fastjson.JSONObject;
import com.chinaunicom.common.exception.BusinessException;
import com.chinaunicom.common.exception.ResponseCode;
import com.chinaunicom.order.domain.gateway.IProductGateway;
import com.chinaunicom.order.domain.model.entity.*;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author guomenghuai
 * @date 2024/1/10
 * @Description
 */
@Slf4j
public abstract class AbstractOrderService implements IOrderService {

    @Resource
    private IProductGateway productGateway;

    @Override
    public PayOrderEntity createOrder(ShopCartEntity shopCartEntity) {
        try {
            log.info("购物车信息：{}", JSONObject.toJSONString(shopCartEntity));
            Long userId = shopCartEntity.getUserId();

            String sellerId = shopCartEntity.getSellerId();

            List<String> skuCodeList = shopCartEntity.getOrderItemList().stream().map(OrderItemEntity::getSkuCode).collect(Collectors.toList());

            // 产品信息
            List<ProductSkuEntity> productSkuList = productGateway.convertProductEntity(skuCodeList, sellerId);
            log.info("调用产品服务获取到产品列表：{}", JSONObject.toJSONString(productSkuList));

            // TODO 如果后续有优惠券，方便扩展
            Integer orderAmount = this.doCalculateOrderAmount(shopCartEntity, productSkuList);
            log.info("模拟调用营销服务计算订单金额：{}", orderAmount);

            CreateOrderEntity createOrderEntity = CreateOrderEntity.builder()
                    .userId(userId)
                    .sellerId(sellerId)
                    .couponId(shopCartEntity.getCouponId())
                    .orderItemList(shopCartEntity.getOrderItemList())
                    .orderAmount(orderAmount)
                    .build();
            // 保存订单
            Long orderId = this.doSaveOrder(createOrderEntity);
            log.info("生成订单号：{}", orderId);

            // 发送订单延迟消息用于支付超时自动关单
            this.doSendPayOrderTimeoutDelayQueue(orderId, userId);

            return PayOrderEntity.builder().orderId(orderId).build();
        } catch (Exception e) {
            log.error("创建订单，已生成微信支付，返回userId：{}，skuCodeList：{}", shopCartEntity.getUserId(),
                    shopCartEntity.getOrderItemList().stream().map(OrderItemEntity::getSkuCode).collect(Collectors.toList()));
            log.error("创建订单异常", e);
            throw new BusinessException(ResponseCode.UNKNOW_ERROR.getCode(), ResponseCode.UNKNOW_ERROR.getMessage());
        }
    }

    @Override
    public PrePayOrderEntity prePayOrder(PrePayOrderRequestEntity payOrderRequest) {
        return null;
    }

    /**
     * 计算订单金额
     * @param shopCartEntity
     * @param productSkuList
     * @return
     */
    protected abstract Integer doCalculateOrderAmount(ShopCartEntity shopCartEntity, List<ProductSkuEntity> productSkuList);

    /**
     * 保存订单
     * @param createOrderEntity
     * @return
     */
    protected abstract Long doSaveOrder(CreateOrderEntity createOrderEntity);

    /**
     * 预支付
     * @param prePayOrderEntity
     * @return
     */
    protected abstract PrePayOrderEntity doPrePayOrder(PrePayOrderRequestEntity prePayOrderEntity);

    /**
     * 发送订单延迟消息
     * @param orderId
     * @param userId
     */
    protected abstract void doSendPayOrderTimeoutDelayQueue(Long orderId, Long userId);

}
